package com.mh.common;

import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private JwtComponent jwtComponent;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if(method.equals("OPTIONS")) return true;

        String authorization = request.getHeader("Authorization");
        if(ObjectUtils.isEmpty(authorization)){
            throw new JwtAuthorizationException("token为空");
        }
        Date expireTime = jwtComponent.getExpireTime(authorization);
        if(expireTime.before(new Date())){
            throw new JwtAuthorizationException("token已过期");
        }
        return true;
    }
}
